/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hss01248.dialogutildemo.slice;

import com.hss01248.dialog.StyledDialog;
import com.hss01248.dialog.Tool;
import com.hss01248.dialog.adapter.SuperRcvAdapter;
import com.hss01248.dialog.adapter.SuperRcvHolder;
import com.hss01248.dialog.bottomsheet.BottomSheetBean;
import com.hss01248.dialog.comp.ProgressDialog;
import com.hss01248.dialog.config.ConfigBean;
import com.hss01248.dialog.interfaces.MyDialogListener;
import com.hss01248.dialog.interfaces.MyItemDialogListener;
import com.hss01248.dialogutildemo.CustomContentHolder;
import com.hss01248.dialogutildemo.ResourceTable;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.*;
import ohos.agp.components.webengine.BrowserAgent;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.*;

/**
 * main ability slice
 */
public class MainAbilitySlice extends AbilitySlice {
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     */
    Ability activity;
    Context context;
    EventHandler handler;
    String msg = "如果你有心理咨询师般的敏锐，你会进一步发现——这个姑娘企图用考研来掩饰自己对于毕业的恐惧。";

    /**
     * construct
     */
    public MainAbilitySlice()
    {
        handler = new EventHandler(EventRunner.getMainEventRunner());
    }

    /**
     * on start
     * @param intent intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_activity_main);
		// --                     button_test_badToken                            --//
        Button button_test_badToken = (Button) findComponentById(ResourceTable.Id_btn_test_badToken);
        if (button_test_badToken != null){
            button_test_badToken.setClickedListener(
                    listener -> presentForResult(new BadTokenAbilitySlice(), new Intent(), 0));
        }

        // 菊花loading
        Button btn_common_progress = (Button)findComponentById(ResourceTable.Id_btn_common_progress);
        btn_common_progress.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                final CommonDialog[] dialog00 = new CommonDialog[1];
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        dialog00[0] =  StyledDialog.buildLoading( "加载中...").show();
                    }
                }).run();

                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        StyledDialog.updateLoadingMsg("jjjjj"+ new Random().nextInt(100),dialog00[0]);
                    }
                },50,2000);
            }
            });

        // md loading
        Button btn_context_progress = (Button)findComponentById(ResourceTable.Id_btn_context_progress);
        btn_context_progress.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                CommonDialog gloablDialog = StyledDialog.buildMdLoading().show();

                handler.postTask(new Runnable() {
                    @Override
                    public void run() {
                        StyledDialog
                                .updateLoadingMsg("jjjjj"+ new Random().nextInt(100),gloablDialog);
                    }
                },3000);
            }
        });

        // horizontal progress
        Button btn_context_progress_h = (Button)findComponentById(ResourceTable.Id_btn_context_progress_h);
        btn_context_progress_h.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                final ProgressDialog dialog= (ProgressDialog) StyledDialog.buildProgress( getString(com.hss01248.dialog.ResourceTable.String_dialogutil_loading),true).setCancelable(false,false).show();
                final int[] progress = {0};
                final Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        progress[0] +=10;
                        StyledDialog.updateProgress(dialog, progress[0],100,"progress",true);
                        if(progress[0]>100){
                            timer.cancel();
                            dialog.destroy();
                        }
                    }
                },500,500);
            }
        });

        // horizontal circle
        Button btn_context_progress_c = (Button)findComponentById(ResourceTable.Id_btn_context_progress_c);
        btn_context_progress_c.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                final ProgressDialog dialog2= (ProgressDialog) StyledDialog.buildProgress( "下载中...",false).show();
                final int[] progress2 = {0};

                final Timer timer2 = new Timer();
                timer2.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        progress2[0] +=10;
                        StyledDialog.updateProgress(dialog2, progress2[0],100,"progress",false);
                        if(progress2[0]>=100){
                            timer2.cancel();
                        }
                    }
                },500,500);
            }
        });

        // material_alert
        Button btn_material_alert = (Button)findComponentById(ResourceTable.Id_btn_material_alert);
        btn_material_alert.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                StyledDialog.buildMdAlert("title", msg,  new MyDialogListener() {
                    @Override
                    public void onFirst() {
                        showToast("onFirst");
                    }

                    @Override
                    public void onSecond() {
                        new ToastDialog(getContext()).setText("onSecond").show();
                        showToast("onSecond");
                    }

                    @Override
                    public void onThird() {
                        showToast("onThird");
                    }


                })
                        .setBtnSize(29)
                        .setForceHeightPercent(0.75f)
                        .setBtnText("i","b","3")
                        .setBtnColor(ResourceTable.Color_colorPrimary,ResourceTable.Color_colorPrimaryDark,ResourceTable.Color_dialogutil_text_gray)
                        .show();
            }
        });


        // ios_alert
        Button btn_ios_alert = (Button)findComponentById(ResourceTable.Id_btn_ios_alert);
        btn_ios_alert.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                StyledDialog.buildIosAlert( "", msg,  new MyDialogListener() {
                    @Override
                    public void onFirst() {
                        showToast("onFirst");
                    }

                    @Override
                    public void onSecond() {
                        new ToastDialog(getContext()).setText("onSecond").show();
                        showToast("onSecond");
                    }

                    @Override
                    public void onThird() {
                        showToast("onThird");
                    }


                })
                        .setBtnText("cancel","copy")
                        .setBtnColor(ResourceTable.Color_dialogutil_text_gray,ResourceTable.Color_colorPrimaryDark,0)
                        .setCustomContentHolder(new CustomContentHolder(StyledDialog.context))
                        .show();
            }
        });


        // ios_alert_vertical
        Button btn_ios_alert_vertical = (Button)findComponentById(ResourceTable.Id_btn_ios_alert_vertical);
        btn_ios_alert_vertical.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                StyledDialog.buildIosAlertVertical( "titlelll", msg,  new MyDialogListener() {
                    @Override
                    public void onFirst() {
                        showToast("onFirst");
                    }

                    @Override
                    public void onSecond() {
                        new ToastDialog(getContext()).setText("onSecond").show();
                        showToast("onSecond");
                    }

                    @Override
                    public void onThird() {
                        showToast("onThird");
                    }


                }).show();
            }
        });


        // ios_bottom_sheet
        Button btn_ios_bottom_sheet = (Button)findComponentById(ResourceTable.Id_btn_ios_bottom_sheet);
        btn_ios_bottom_sheet.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                final List<String> strings = new ArrayList<>();
                strings.add("1");
                strings.add("2");
                strings.add(msg);
                strings.add("4");
                strings.add("5");

                StyledDialog.buildBottomItemDialog( strings, "好的",  new MyItemDialogListener() {
                    @Override
                    public void onItemClick(CharSequence text, int position) {
                        showToast(text.toString());
                    }

                    @Override
                    public void onBottomBtnClick() {
                        showToast("onItemClick");
                    }
                })
                        .show();
            }
        });

        // ios_center_list
        Button btn_ios_center_list = (Button)findComponentById(ResourceTable.Id_btn_ios_center_list);
        btn_ios_center_list.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                final List<String> strings = new ArrayList<>();
                strings.add("1");
                strings.add("2");
                strings.add(msg);
                strings.add("4");
                strings.add("5");
                strings.add(msg);

                StyledDialog.buildIosSingleChoose(strings, new MyItemDialogListener() {
                    @Override
                    public void onItemClick(CharSequence text, int position) {
                        showToast(text.toString());
                    }

                    @Override
                    public void onBottomBtnClick() {
                        showToast("onItemClick");
                    }
                })
                        .setTitle("任选一个")
                        .show();
            }
        });


        // input
        Button btn_input = (Button)findComponentById(ResourceTable.Id_btn_input);
        btn_input.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                StyledDialog.buildNormalInput("登录", "请输入用户名", "请输入密码",
                        "dashedsen", "51420",  new MyDialogListener() {
                            @Override
                            public void onFirst() {

                            }

                            @Override
                            public void onSecond() {

                            }

                            @Override
                            public boolean onInputValid(CharSequence input1, CharSequence input2, TextField editText1, TextField editText2) {
                                showToast("input1--input2:"+input1+"--"+input2 +"is not accepted!");
                                return false;
                            }

                            @Override
                            public void onGetInput(CharSequence input1, CharSequence input2) {
                                super.onGetInput(input1, input2);
                                showToast("input1:"+ input1 +"--input2:"+input2);
                            }
                        })
                        .setInput2HideAsPassword(false)
                        .setCancelable(true,true)
                        .show();
            }
        });

        // material_input
        Button btn_material_input = (Button)findComponentById(ResourceTable.Id_btn_material_input);
        btn_material_input.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                StyledDialog.buildMdInput("登录", "fefe", "请输入密码",
                        "fee544es", "fesfeee",  new MyDialogListener() {
                            @Override
                            public void onFirst() {

                            }

                            @Override
                            public void onSecond() {

                            }

                            @Override
                            public boolean onInputValid(CharSequence input1, CharSequence input2, TextField editText1, TextField editText2) {
                                showToast("input1--input2:"+input1+"--"+input2 +"is not accepted!");
                                return false;
                            }

                            @Override
                            public void onGetInput(CharSequence input1, CharSequence input2) {
                                super.onGetInput(input1, input2);
                                showToast("input1:"+ input1 +"--input2:"+input2);
                            }
                        })
                        .setInput2HideAsPassword(true)
                        .setCancelable(true,true)
                        .show();
            }
        });

        // multi_choose
        Button btn_multichoose = (Button)findComponentById(ResourceTable.Id_btn_multichoose);
        btn_multichoose.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String[] words = new String[]{"12","78","45","89","88","00"};


                StyledDialog.buildMdMultiChoose( "xuanze", words, new ArrayList<Integer>(),  new MyDialogListener() {
                    @Override
                    public void onFirst() {

                    }

                    @Override
                    public void onSecond() {

                    }

                    @Override
                    public void onChoosen( List<Integer> selectedIndex, List<CharSequence> selectedStrs,boolean[] states) {
                        super.onChoosen( selectedIndex, selectedStrs,states);
                    }

                    @Override
                    public void onGetChoose(boolean[] states) {
                        super.onGetChoose(states);
                    }
                }).setTitleColor(com.hss01248.dialog.ResourceTable.Color_dialogutil_ios_btntext_blue).show();
            }
        });


        // single_choose
        Button btn_singlechoose = (Button)findComponentById(ResourceTable.Id_btn_singlechoose);
        btn_singlechoose.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String[] words2 = new String[]{"12","78","45","89","88","00"};
                StyledDialog.buildMdSingleChoose("单选", 2, words2,  new MyItemDialogListener() {
                    @Override
                    public void onItemClick(CharSequence text, int position) {
                        showToast(text + "--" + position);
                    }
                }).setDismissAfterResultCallback(false).show();
            }
        });

        // md_bottomsheet
        Button btn_md_bs = (Button)findComponentById(ResourceTable.Id_btn_md_bs);
        btn_md_bs.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String[] words3 = new String[]{"12","78","45","89","88","00"};
                List<String> datas = Arrays.asList(words3);

                // final BottomSheetDialog dialog = new BottomSheetDialog(this);
                ListContainer recyclerView = new ListContainer(StyledDialog.context);
                recyclerView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
                recyclerView.setHeight(800);
                DirectionalLayoutManager layoutManager = new DirectionalLayoutManager();
                layoutManager.setOrientation(Component.VERTICAL);
                recyclerView.setLayoutManager(layoutManager);
                SuperRcvAdapter adapter = new SuperRcvAdapter(StyledDialog.context) {
                    @Override
                    protected SuperRcvHolder generateCoustomViewHolder(int viewType) {

                        return new SuperRcvHolder<String>(inflate(ResourceTable.Layout_item_text)) {

                            Button mButton;
                            @Override
                            public void assignDatasAndEvents(Context context, final String data) {
                                if (mButton==null){
                                    mButton = (Button) rootView.findComponentById(ResourceTable.Id_btnee);
                                }
                                mButton.setText(data);
                                mButton.setClickedListener(new Component.ClickedListener() {
                                    @Override
                                    public void onClick(Component v) {
                                        showToast(data);
                                    }
                                });
                            }
                        };
                    }
                };
                adapter.addAll(datas);
                adapter.addAll(datas);
                adapter.addAll(datas);
                recyclerView.setItemProvider(adapter);

                StyledDialog.buildCustomBottomSheet(recyclerView).show();//不好建立回调
            }
        });

        // md_bottomsheet_listview
        Button btn_md_bs_listview = (Button)findComponentById(ResourceTable.Id_btn_md_bs_listview);
        btn_md_bs_listview.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                List<BottomSheetBean> datas2 = new ArrayList<>();

                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"1"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"222"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"333333"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"444"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"55"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"666"));

                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"7777"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"fddsf"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"67gfhfg"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"oooooppp"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"7777"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"8"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"9"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"10"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"11"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"12"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"13"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"14"));




                StyledDialog.buildBottomSheetLv( "拉出来溜溜", datas2, "this is cancle button", new MyItemDialogListener() {
                    @Override
                    public void onItemClick(CharSequence text, int position) {
                        showToast(text+"---"+position);
                    }
                }).setBottomSheetDialogMaxHeightPercent(0.3f).show();
            }
        });

        // md_bottomsheet_gridview
        Button btn_md_bs_Gridview = (Button)findComponentById(ResourceTable.Id_btn_md_bs_Gridview);
        btn_md_bs_Gridview.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                List<BottomSheetBean> datas2 = new ArrayList<>();

                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"1"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"222"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"333333"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"444"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"55"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"666"));

                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"7777"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"fddsf"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"67gfhfg"));
                datas2.add(new BottomSheetBean(ResourceTable.Media_ic_launcher,"oooooppp"));


                StyledDialog.buildBottomSheetGv( "", datas2, "this is cancle button",4, new MyItemDialogListener() {
                    @Override
                    public void onItemClick(CharSequence text, int position) {
                        showToast(text+"---"+position);
                    }
                }).setHasBehaviour(false).show();
            }
        });

        // customview_webview
        Button btn_customview = (Button)findComponentById(ResourceTable.Id_btn_customview);
        btn_customview.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                LayoutScatter scatter = LayoutScatter.getInstance(StyledDialog.context);
                ComponentContainer customView = (ComponentContainer) scatter.parse(ResourceTable.Layout_customview,null, false);
                final ConfigBean bean = StyledDialog.buildCustom(customView, LayoutAlignment.CENTER)
                        .setForceWidthPercent(1.0f)
                        .setHasShadow(false);
                final CommonDialog dialog1 =   bean.show();
                WebView webView = (WebView) customView.findComponentById(ResourceTable.Id_webview);
                final Text textView = (Text) customView.findComponentById(ResourceTable.Id_tv_title);
                webView.load("http://www.baidu.com");

                webView.setWebAgent(new WebAgent(){
                    @Override
                    public void onPageLoaded(WebView view, String url) {
                        super.onPageLoaded(view, url);
                        Tool.adjustWH(dialog1,bean);
                    }
                });
                webView.setBrowserAgent(new BrowserAgent(StyledDialog.context){
                    @Override
                    public void onTitleUpdated(WebView view, String title) {
                        super.onTitleUpdated(view, title);
                        textView.setText(title);
                    }
                });
            }
        });
        String customMsg = "维吾尔文（中国）：values-ug-rCN" +
                "\n" +
                "        中文（中国）：values-zh-rCN" +
                "\n" +
                "        中文（台湾）：values-zh-rTW" +
                "\n" +
                "        中文（香港）：values-zh-rHK" +
                "\n" +
                "        英语（美国）：values-en-rUS" +
                "\n" +
                "        英语（英国）：values-en-rGB";
        // customview_layout
        Button btn_customview2 = (Button)findComponentById(ResourceTable.Id_btn_customview2);
        btn_customview2.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                LayoutScatter scatter = LayoutScatter.getInstance(StyledDialog.context);
                ComponentContainer customView2 = (ComponentContainer) scatter.parse(ResourceTable.Layout_customview2,null, false);
                Text text = (Text)customView2.findComponentById(ResourceTable.Id_textView2);
                text.setText(customMsg);
                StyledDialog.buildCustom(customView2,LayoutAlignment.HORIZONTAL_CENTER).setForceWidthPercent(0.90f).setForceHeightPercent(0.8f).show();
            }
        });

        // ad
        Button btn_ad = (Button)findComponentById(ResourceTable.Id_btn_ad);
        btn_ad.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                LayoutScatter scatter = LayoutScatter.getInstance(StyledDialog.context);
                ComponentContainer customView3 = (ComponentContainer) scatter.parse(ResourceTable.Layout_customview2,null, false);
                Text text = (Text)customView3.findComponentById(ResourceTable.Id_textView2);
                text.setText(customMsg);
                StyledDialog.buildCustomAsAdStyle(customView3,LayoutAlignment.RIGHT|LayoutAlignment.TOP)
                        .setxMarginLR(15)
                        .setxMarginTB(30)
                        .setxWidth(55).show();
            }
        });

        // ad_title_msg
        Button btn_ad_msg = (Button)findComponentById(ResourceTable.Id_btn_ad_msg);
        btn_ad_msg.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                StyledDialog.buildAlertAsAdStyle("title","hahahhahahahahha",LayoutAlignment.HORIZONTAL_CENTER|LayoutAlignment.BOTTOM)
                        .setxWidth(25).show();
            }
        });
    }
    private void showToast(String text)
    {
        new ToastDialog(getContext()).setText(text).show();
    }

    /**
     * on active
     */
    @Override
    public void onActive() {
        super.onActive();
    }

    /**
     * on foreground
     * @param intent intent
     */
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
